package com.lostandfound.filter;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


/**
 * Application Lifecycle Listener implementation class OnlineCounter
 *
 */
@WebListener
public class OnlineCounter extends HttpServlet implements HttpSessionListener {
       
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static int onLineSessionCounter = 0;
	private static int totalLoginCounter = 0;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public OnlineCounter() {
        super();
    }

	/**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent arg0)  { 
    	
    	onLineSessionCounter++;//当前在线人数+1
    	totalLoginCounter++;//总访问量
    	//HttpSession session = 
    	ServletContext context = arg0.getSession().getServletContext();
    	System.out.println(onLineSessionCounter);
    	context.setAttribute("onLineCount", onLineSessionCounter);
    	context.setAttribute("todayCount", totalLoginCounter);
    	OnLineUsers.getInstance().addSession(arg0.getSession());;  
    	//= session;
    }

	/**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent arg0)  { 
    	onLineSessionCounter--;//当前在线人数-1
    	System.out.println(onLineSessionCounter);
    	ServletContext context = arg0.getSession().getServletContext();
    	context.setAttribute("onLineCount", onLineSessionCounter);
    	OnLineUsers.getInstance().removeSession(arg0.getSession().getId());
    }
    
    /**
     * 获取当前在线用户个数
     * @return
     */
    public static int getOnlineSession(){
    	return onLineSessionCounter;
    }
    
    /**
     * 获取当天用户登录量
     * @return
     */
    public static int getTotalCounter(){
    	return totalLoginCounter;
    }
	
}
